package DataStr.homework04;

public class h1 {
    //为单链表类LinkList补充一个用于在位置i插入数据x的方法
    //节点类
    static class Node {
        Object date;
        Node next;

        Node(Object date) {
            this.date = date;
            this.next = null;
        }
    }

        public static class LinkList {
            //链表类
            public Node head;

            public LinkList() {
                head = null;
            }

            public void add(int i, Object data) throws Exception {
                //判断插入位置是否合法
                if (i < 1) {
                    throw new Exception("插入位置必须大于1");
                }
                Node newNode = new Node(data);
                //特殊情况，如果插入位置为头部位置
                if (i == 1) {
                    newNode.next = head;
                    head = newNode;
                    return;
                }
                Node current=head;
                int index=1;
                //找到插入位置的前一个结点
                while(current!=null&&index<i-1){
                    current=current.next;
                    index++;
                }
                if(current==null){
                    throw new Exception("插入位置超出链表长度");
                }
                //插入新节点
                newNode.next=current.next;
                current.next=newNode;
            }
            //打印链表
            public void print(){
                Node current=head;
                while (current!=null){
                    System.out.print(current.date+" ");
                    current=current.next;
                }
                System.out.println();
            }
        }
    public static void main(String[] args) {
        try{
            LinkList list=new LinkList();
            list.add(1,"a");
            list.add(2,"b");
            list.add(3,"c");
            list.add(4,"d");
            list.print();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    }
